package leetcode.f1t100;

/**
 * 使用数组代表整数, 返回加一后的值
 * https://leetcode.com/problems/plus-one/
 *
 * @Author lichongxiao
 * @Date 2022/11/22 15:31
 */
public class Q66_PlusOne {
    public int[] plusOne(int[] digits) {
        digits[digits.length - 1]++;
        for (int i = digits.length - 1; i > 0; i--) {
            if (digits[i] > 9) {
                digits[i - 1]++;
                digits[i] %= 10;
            } else {
                break;
            }
        }
        if (digits[0] <= 9) {
            return digits;
        }
        int[] ans = new int[digits.length + 1];
        ans[0] = 1;
        digits[0] %= 10;
        for (int i = 0; i < digits.length; i++) {
            ans[i + 1] = digits[i];
        }
        return ans;
    }

    public int[] plusOneFaster(int[] digits) {
        int n = digits.length;
        for (int i = n - 1; i >= 0; i++) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        int[] ans = new int[n + 1];
        ans[0] = 1;
        return ans;
    }
}
